package com.proton.carepatchtemp.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.adapter.ShareHistoryAdapter;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.table.ShareHistory;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.DeviceCenter;
import com.sdsmdg.tastytoast.TastyToast;

import java.util.ArrayList;
import java.util.List;

public class DeviceShareActivity extends BaseActivity {

    private ImageButton mBtnBack;
    /**
     * 对方的手机号
     */
    private EditText mEtPhoneNumber;
    private RecyclerView mRcvShareHistory;
    private LinearLayoutManager mLinearLayoutManager;
    private ShareHistoryAdapter mShareHistoryAdapter;

    private List<ShareHistory.SharelistBean> mShareHistories = new ArrayList<>();

    private String deviceId;
    private String profileId;
    private ImageView mIvNumberContent;
    private FrameLayout mFrlShareDevice;

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            case Codes.DEVICE_SHARE_HISTORY:
                if (event.isSuccess()) {
                    ShareHistory temp = (ShareHistory) event.getObj();
                    if (null != temp && null != temp.getSharelist()) {
                        mShareHistories.clear();
                        mShareHistories.addAll(temp.getSharelist());
                        mShareHistoryAdapter.notifyDataSetChanged();
                    }
                } else {
                    TastyUtils.makeTextShort(event.getMsg(), TastyToast.DEFAULT);
                }

                break;
            case Codes.DEVICE_SHARE:
                if (event.isSuccess()) {
                    TastyUtils.makeTextShort(R.string.string_share_success, TastyToast.SUCCESS);
                    mEtPhoneNumber.setText("");
                } else {
                    if (event.getMsg().equalsIgnoreCase("null")) {
                        TastyUtils.makeTextShort(R.string.string_no_regist, TastyToast.ERROR);
                    } else {
                        TastyUtils.makeTextShort(getString(R.string.string_share_fail) + event.getMsg(), TastyToast.ERROR);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_share);
        initView();
        setListener();

        LogUtils.d(getIntent().getExtras());

        deviceId = getIntent().getExtras().getString(Extras.DEVICE_ID);
        profileId = getIntent().getExtras().getString(Extras.PRF_PROFILEID);
        if (TextUtils.isEmpty(deviceId) || TextUtils.isEmpty(profileId)) {
            TastyUtils.makeTextShort(R.string.string_get_measure_info_fail, TastyToast.ERROR);
            finish();
        }
        mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mShareHistoryAdapter = new ShareHistoryAdapter(this, mShareHistories, Long.parseLong(profileId));
        mRcvShareHistory.setLayoutManager(mLinearLayoutManager);
        mRcvShareHistory.setAdapter(mShareHistoryAdapter);

        DeviceCenter.getShareHistory(deviceId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            ContentResolver reContentResolverol = getContentResolver();
            Uri contactData = data.getData();
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(contactData, null, null, null, null);
            cursor.moveToFirst();
            String username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                    null,
                    null);
            while (phone.moveToNext()) {
                String usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                mEtPhoneNumber.setText(usernumber.replaceAll(" ", ""));
            }

        }
    }

    @Override
    protected void setListener() {
        mBtnBack.setOnClickListener(v -> {
            finish();
        });

        mFrlShareDevice.setOnClickListener(v -> {
            if (TextUtils.isEmpty(mEtPhoneNumber.getText())) {
                TastyUtils.makeTextShort(R.string.string_phone_can_not_be_null, TastyToast.CONFUSING);
                return;
            }

            if (mEtPhoneNumber.getText().length() != 11) {
                TastyUtils.makeTextShort(R.string.string_phone_error, TastyToast.CONFUSING);
                return;
            }
            DeviceCenter.share(deviceId, mEtPhoneNumber.getText().toString(), Long.parseLong(profileId));
        });

        mIvNumberContent.setOnClickListener(v -> {
            startActivityForResult(new Intent(
                    Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 0);
        });
    }


    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    private void initView() {
        mBtnBack = findViewById(R.id.btn_back);
        mEtPhoneNumber = findViewById(R.id.et_phone_number);
        mRcvShareHistory = findViewById(R.id.rcv_share_history);
        mIvNumberContent = findViewById(R.id.iv_number_content);
        mFrlShareDevice = findViewById(R.id.frl_share_device);
    }
}
